import {_decorator, Component, Node, TiledMap, resources, Prefab, instantiate, v3, renderer, Camera} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('MapController')
export class MapController extends Component {

    @property(Camera)
    camera: Camera = null;

    player: Node = null;

    start() {
        // 获取地图
        let map = this.node.getComponent(TiledMap);
        // 获取地图层
        // map.getLayer("roadLayer");
        // 获取对象层
        let playerLayer = map.getObjectGroup("objectLayer");
        // 获取玩家对象
        let playerObj = playerLayer.getObject("player");

        // 加载预设体
        resources.load("prefabs/player", Prefab, (err: Error, data: Prefab) => {
            if (!err) {
                // 玩家
                this.player = instantiate(data);
                // 设置父节点
                this.player.setParent(this.node.children[2].children[0]);
                // 设置玩家坐标
                // this.player.setPosition(v3(playerObj.x, playerObj.y));
                this.player.setPosition(v3(0, 0));
                console.log(playerObj.x, playerObj.y);// 416 384
                console.log(this.player.position.x, this.player.position.y);// 416 384
                console.log(this.camera.camera.position.x, this.camera.camera.position.y);// 240 160
                console.log(this.camera.node.position.x, this.camera.node.position.y);// 0 0
            }
        });
    }

    update(deltaTime: number) {
        // 当玩家存在时
        if (this.player) {
            // 相机跟随
            // this.camera.node.setPosition(v3(this.player.position.x - 240, this.player.position.y - 160));
            this.camera.node.setPosition(v3(this.player.position.x, this.player.position.y));
        }
    }
}

